<template>
  <div class="brand-container">
    <el-card>
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="showBrandDialog"
          >添加</el-button
        >
        <el-table
          style="width: 100%"
          stripe
          border
          class="brand-table"
          :data="brandList"
        >
          <el-table-column label="序号" width="80" type="index" />
          <el-table-column prop="tmName" label="品牌名称" />
          <el-table-column prop="prop" label="品牌logo">
            <template #default="{ row }">
              <el-image
                style="width: 120px; height: 100px"
                :src="row.logoUrl"
                :preview-src-list="[row.logoUrl]"
                fit="contain"
              >
                <div slot="error" class="image-slot">
                  <img
                    src="@/assets/loadError/dijia.gif"
                    alt=""
                    style="width: 120px; height: 100px"
                  />
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作">
            <template #default="{ row }">
              <el-button
                size="mini"
                icon="el-icon-edit"
                type="primary"
                @click="showBrandDialog(row)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="onDelete(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :disabled="ispaginationDisable"
          class="brand-pagination"
          :current-page.sync="currentPage"
          :page-sizes="[3, 5, 10]"
          :page-size.sync="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
          @size-change="onGetBrandTableData"
          @current-change="onGetBrandTableData"
        />
      </div>
    </el-card>
    <el-dialog
      :title="form.id ? '修改商品' : '添加商品'"
      :visible.sync="isShowBrandDialog"
      @close="handleDialogClose"
    >
      <el-form
        ref="brandform"
        :model="form"
        label-width="100px"
        style="width: 90%"
        :rules="brandFormRules"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="form.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowBrandDialog = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="isLoading"
          @click="handleAddOrEditBrand"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { brandFormRules } from "utils/elementFormRules";
export default {
  name: "BrandManage",
  components: {},
  props: {},
  data() {
    return {
      currentPage: 1,
      pageSize: 3,
      total: 0,
      brandList: [],
      // 是否禁用分页器
      ispaginationDisable: false,
      // 添加修改对话框的显示与隐藏
      isShowBrandDialog: false,
      form: {
        id: "",
        tmName: "",
        logoUrl: "",
      },
      // 是否正在新增或者修改商品属性
      isLoading: false,
      // 商品表单验证
      brandFormRules,
    };
  },
  computed: {},
  watch: {},
  created() {
    this.onGetBrandTableData();
  },
  mounted() {},
  methods: {
    // 获取品牌数据
    async onGetBrandTableData() {
      const { currentPage, pageSize } = this;
      this.ispaginationDisable = true;
      const res = await this.$api.brandManage.getBrandTableData(
        currentPage,
        pageSize
      );
      if (res.code === 200) {
        this.brandList = res?.data?.records || [];
        this.total = res?.data?.total || 0;
      }
      this.ispaginationDisable = false;
    },
    // 显示对话框
    showBrandDialog(brandInfo) {
      if (brandInfo.id) {
        this.form = { ...brandInfo };
      }
      this.isShowBrandDialog = true;
    },
    handleAvatarSuccess(res, file) {
      this.form.logoUrl = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 新增或者编辑
    handleAddOrEditBrand() {
      this.$refs.brandform.validate(async (flag) => {
        if (!flag) {
          return;
        } else {
          this.isLoading = true;
          const res = await this.$api.brandManage.addOrEditBrand(this.form);
          if (res.code === 200) {
            this.onGetBrandTableData();
            this.$message.success(
              this.form.id ? "修改商品属性成功" : "新增商品信息成功"
            );
            this.isShowBrandDialog = false;
          } else {
            this.$message.error(res.data);
          }
          this.isLoading = false;
        }
      });
    },
    // 对话框关闭时的回调
    handleDialogClose() {
      this.form.id = "";
      this.$refs.brandform.resetFields();
    },
    async onDelete(brandInfo) {
      try {
        await this.$confirm(`确定要删除${brandInfo.tmName}吗?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        console.log(this.$api.brandManage);
        const res = await this.$api.brandManage.removeBrand(brandInfo.id);
        if (res.code === 200) {
          this.$message.success("删除成功");
          this.onGetBrandTableData();
        } else {
          this.$message.error("删除失败");
        }
      } catch (error) {
        if (error === "cancel") {
        } else {
          console.log(error);
          this.$message.error(error.message);
        }
      }
    },
  },
};
</script>

<style scoped lang="scss">
.brand-table {
  margin-top: 30px;
}
.brand-pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
